import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Button, Drawer, Form, Input, message, Select, Space, Upload, Image } from 'antd';
import { ProTable, ProColumns, FooterToolbar, PageContainer } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { fetchSolutionList, deleteSolution, createSolution, updateSolution } from '@/services/ant-design-pro/solution';
import { upload } from '@/services/ant-design-pro/api';
import { UploadOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import SolutionCategoryMenu from './components/Menu'; // 假设有一个解决方案分类菜单组件
import ImageUpload from '@/components/ImageUpload';
const { Option } = Select;

const SolutionList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<any | undefined>(undefined);
  const [form] = Form.useForm();
  const [imageUrl, setImageUrl] = useState<string | undefined>(undefined);
  const [activeKey, setActiveKey] = useState<string>('1');
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const [key, setKey] = useState('1');
  const { run: delRun, loading } = useRequest(deleteSolution, {
    manual: true,
    onSuccess: () => {
      actionRef.current?.reload();
      message.success('删除成功');
    },
    onError: () => {
      message.error('删除失败，请重试');
    },
  });

  const handleCategorySelect = (key: string) => {
    setKey(key);
    actionRef.current?.reload();
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await deleteSolution({ id });
      if (response) {
        message.success('删除成功');
        actionRef.current?.reload();
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleRemove = useCallback(
    async (selectedRows: any[]) => {
      if (selectedRows.length === 0) {
        message.warning('请先选择要删除的项');
        return;
      }
      await delRun({ ids: selectedRows.map((row) => row.id) });
    },
    [delRun],
  );

  const columns: ProColumns<any>[] = [
    {
      title: '标题',
      dataIndex: 'attributeTitle',
      width: 100,
      ellipsis: true,
      render: (text, record) => (
        <a onClick={() => {
          setCurrentRecord(record);
          form.setFieldsValue(record);
          setImageUrl(record.attributeUrl);
          setDrawerVisible(true);
        }}>{text}</a>
      ),
    },
 
    {
      title: '内容描述',
      dataIndex: 'typeTitle',
      valueType: 'textarea',
      ellipsis:true,
      width: 100,
      search: false
    },
    
    {
      title: '简介',
      dataIndex: 'attributeSubtitle',
      search: false,
      ellipsis: true,
      hidden: activeKey !== '2' ? true : false,
      width:100
    },

    {
      title: '解决方案类型',
      dataIndex: 'type',
      ellipsis: true,
      width: 100,
      hidden:true,
      valueEnum: {
        1: { text: '服务及优势' },
        2: { text: '服务案例' },
        3: { text: '解决方案适用场景' },
      },
      search: false
    },
    {
      title: '图片',
      width: activeKey === '1' ? 60 : 110,
      dataIndex: 'attributeUrl',
      render: (text) => <Image src={text} alt="图片" style={{ 'objectFit': 'contain ', width: activeKey === '1' ? 40 : 100, height: 40 }} />,
      search: false
    },
    {
      title: '排序',
      dataIndex: 'sort',
      search: false,
      width: 70
    },
    {
      title: '操作',
      width: 120,
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue(record);
            setImageUrl(record.attributeUrl);
            setDrawerVisible(true);
          }}
        >
          编辑
        </a>,
        <a key="delete" onClick={() => handleDelete(record.id)}>删除</a>,
      ],
    },
  ];

  const handleUpload = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await upload(formData);
      setImageUrl(response.data[0]);
      form.setFieldsValue({ attributeUrl: response.data[0] });
    } catch (error) {
      message.error('上传图片失败，请重试');
    }
  };

  
  const imageUploadPropsMap = {
    '1': { maxWidth: 64, maxHeight: 64 },
    '2': { maxWidth: 1920, maxHeight: 700 },
    '3': { maxWidth: 412, maxHeight: 274 },
  };

  const getImageUploadProps = (activeKey: string) => {
    return imageUploadPropsMap[activeKey] || {};
  };


  return (
    <>
     <PageContainer header={{ title: '' }}>
      <ProTable<any>
        headerTitle="解决方案列表"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              setCurrentRecord(undefined);
              form.resetFields();
              setImageUrl(undefined);
              setDrawerVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        request={(params) => fetchSolutionList({ ...params, type: activeKey, solutionId: key })}
        columns={columns}
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <SolutionCategoryMenu selectedKey={key} onCategorySelect={handleCategorySelect} />
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              {
                key: '1',
                label: <span>服务及优势</span>,
              },
              {
                key: '2',
                label: <span>服务案例</span>,
              },
              {
                key: '3',
                label: <span>解决方案</span>,
              },
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}
      />

      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={() => {
              handleRemove(selectedRowsState);
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        title={currentRecord ?  ('编辑'+ (activeKey === '1' ? '服务及优势' : activeKey === '2' ? '服务案例' : '解决方案')) : ('新建'+ (activeKey === '1' ? '服务及优势' : activeKey === '2' ? '服务案例' : '解决方案'))}
        width={600}
        open={drawerVisible}
        onClose={() => setDrawerVisible(false)}
        footer={
          <Space>
            <Button onClick={() => setDrawerVisible(false)}>取消</Button>
            <Button
              type="primary"
              onClick={() => {
                form.validateFields().then(async (values) => {
                  if (currentRecord) {
                    await updateSolution({ ...currentRecord, ...values, attributeUrl: imageUrl });
                  } else {
                    await createSolution({ ...values, attributeUrl: imageUrl, solutionId: key, type: activeKey });
                  }
                  setDrawerVisible(false);
                  message.success('提交成功');
                  actionRef.current?.reload();
                });
              }}
            >
              提交
            </Button>
          </Space>
        }
      >
        <Form form={form} layout="vertical">
          {activeKey === '1' && (<Form.Item
            name="attributeTitle"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="强输入标题" />
          </Form.Item>)}
          {activeKey === '2' && (<><Form.Item
            name="attributeTitle"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="强输入标题" />
          </Form.Item>
          <Form.Item
              name="typeTitle"
              label="导航标题"
              rules={[{ required: true, message: '请输入导航标题' }]}
            >
              <Input placeholder="导航标题" />
            </Form.Item>
            <Form.Item
              name="attributeSubtitle"
              label="描述"
              rules={[{ required: true, message: '请输入描述' }]}
            >
              <Input.TextArea placeholder="请输入简介" rows={4}/>
            </Form.Item>
           </>
          )}

          {activeKey === '3' && (<><Form.Item
            name="attributeTitle"
            label="标题"
            rules={[{ required: true, message: '请输入标题' }]}
          >
            <Input placeholder="请输入标题" />
          </Form.Item>
          </>
          )}

          <Form.Item
            name="sort"
            label="排序"
          >
            <Input type="number" placeholder="请输入排序" />
          </Form.Item>
          <Form.Item hidden={true}
            name="type"
            label="解决方案类型"
          >
            <Select placeholder="请选择解决方案类型">
              <Option value="1">服务及优势</Option>
              <Option value="2">服务案例</Option>
              <Option value="3">解决方案适用场景</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="attributeUrl"
            label="图片"
          >
            <ImageUpload maxWidth={getImageUploadProps(activeKey).maxWidth} maxHeight={getImageUploadProps(activeKey).maxHeight} value={imageUrl} onChange={(url) => setImageUrl(url)} />
          </Form.Item>
          <Form.Item
            name="alt"
            label="图片alt"
          >
            <Input />
          </Form.Item>
        </Form>
      </Drawer>
      </PageContainer>
    </>
   
  );
};

export default SolutionList;